package com.jams.goodox.activity.login;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.Utils;
import com.jams.goodox.widget.EditTextWithDel;

import org.json.JSONObject;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.jams.goodox.utils.Utils.isPhoneNum;

/**
 * 获取验证码
 */
public class GetCodeActivity extends BaseActivity {

    private static final String TAG = "GetCodeActivity";
    @Bind(R.id.edit_tel)
    EditTextWithDel editTel;
    @Bind(R.id.edit_code)
    EditTextWithDel editCode;

    @Bind(R.id.img_agreement)
    ImageView imgAgreement;
    @Bind(R.id.tx_send_verification)
    TextView txSendVerification;

    @Bind(R.id.next_step)
    TextView next_step;


    private Intent intent;
    private String tel;
    private int from = -1;

    private static final String TEL_LENGTH = "请输入11位手机号";
    private static final String CODE_NOT_HAVE = "请输入验证码";
    private static final String CODE_LENGTH = "验证码错误";
    private static final String PASS_NOT_HAVE = "请输入6-12位密码";
    private static final String PASS_FORMAT = "密码请使用6-12位英文或数字";

    private static final String NOT_AGREEMENT = "请勾选阅读并勾选用户协议";

    private boolean isPassShow = false;//标示密码是否可见
    private boolean isAgreed = true;

    private static final int Time_Close = 60;//倒计时持续多少秒

    @Override
    protected int getLayoutId() {
        return R.layout.activity_getcode;
    }

    @Override
    protected void init() {
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_theme));//沉侵式头部
        StyleUtil.titleBackKey(this, "获取验证码");
//
        from = getIntent().getIntExtra("from",-1);
    }

    @OnClick({R.id.ler_back,  R.id.tx_send_verification,  R.id.next_step, R.id.img_agreement, R.id.tx_user_agreement })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tx_send_verification:
                sendVerificationCode();
                break;
            case R.id.next_step:

                if(TextUtils.isEmpty(editTel.getText())
                        || TextUtils.isEmpty(editCode.getText())){
                    ToastUtil.show("请输入手机号以及验证码");
                    return;
                }

                if(from == 0){
                    intent = new Intent(this, RegistActivity.class);
                    intent.putExtra("mobile",editTel.getText().toString());
                    intent.putExtra("smsVerCode",editCode.getText().toString());
                }else {
                    intent = new Intent(this, ModifyPwdActivity.class);
                    intent.putExtra("mobile", editTel.getText().toString());
                    intent.putExtra("smsVerCode",editCode.getText().toString());
                }
                startActivity(intent);
                //register();
                break;
        }
    }

    /**
     * 发送验证码
     */
    private void sendVerificationCode() {
        //手机长度及验证
        tel = editTel.getText().toString().trim();
        if (!isPhoneNum(tel)) {
            ToastUtil.show(this, TEL_LENGTH);
            return;
        }
        txSendVerification.setEnabled(false);

        clearMap();
        String pData = "mobile:" + tel;
        params.put("requestData", "{" + pData +"}");

        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading();

        createCallService(LoginService.class).getSmsCode(body).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                txSendVerification.setEnabled(true);

                try {
                    String data = response.body().string();
                    Log.d(TAG, "data = " + data);
                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code")){
                        next_step.setEnabled(true);
                        Utils.countDown(Time_Close, txSendVerification, new Utils.BaseResult() {
                            @Override
                            public void onStart() {
                                txSendVerification.setEnabled(false);
                                //txSendVerification.setBackgroundResource(R.drawable.bg_cancel_gray_deep);
                                //txSendVerification.setTextColor(ContextCompat.getColor(GetCodeActivity.this, R.color.white));
                            }

                            @Override
                            public void onResult(Boolean t) {
                                txSendVerification.setEnabled(true);
                                txSendVerification.setText("获取验证码");
                                //txSendVerification.setBackgroundResource(R.drawable.bg_cancel_theme);
                                //txSendVerification.setTextColor(ContextCompat.getColor(GetCodeActivity.this, R.color.font_color_black));
                            }
                        });
                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }



                } catch ( Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                txSendVerification.setEnabled(true);
                ToastUtil.show("failure:" + t.getMessage());
            }
        });

    }

}
